package com.atguigu.eduorder.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.atguigu.eduorder.service.PayLogService;
import com.atguigu.eduorder.utils.HttpClient;
import com.atguigu.eduorder.utils.ZfbPayUtils;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class PayLogServiceImpl implements PayLogService {

//    @Autowired
//    private OrderService orderService;

    //生成微信支付二维码
    @Override
    public Map createNative(String orderNo) {
        try {
            //1.根据订单号查询订单信息
            //TODO :根据订单号查询订单信息
    //        QueryWrapper<Order> wrapper = new QueryWrapper<>();
    //        wrapper.eq("order_no",orderNo);
    //        Order order = orderService.getOne(wrapper);

            //2使用map设置生成二维码的参数
            Map m = new HashMap();
            m.put("appid", "wx74862e0dfcf69954");//关联的公众号
            m.put("mch_id", "1558950191");//商户号
            m.put("nonce_str", WXPayUtil.generateNonceStr());//生成随机字符串
            m.put("body","java开发");//order.getCourseTitle()课程标题
            m.put("out_trade_no", orderNo);//订单号
            //m.put("total_fee", order.getTotalFee().multiply(new BigDecimal("100")).longValue()+"");
            m.put("total_fee","0.01");//价格（上面是将价格转换为字符串）
            m.put("spbill_create_ip", "127.0.0.1");
            m.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");
            m.put("trade_type", "NATIVE");

            //3.发送httpclient请求,传递参数xml格式，微信支付提供的固定的地址
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //设置xml格式的参数
            client.setXmlParam(WXPayUtil.generateSignedXml(m,"T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            //执行请求发送
            client.post();

            //4.得到发送请求返回的结果
            //返回内容是xml格式返回
            String xml = client.getContent();
            //把xml格式转换map集合，把map集合返回
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);

            //最终返回数据的封装
            Map map = new HashMap();
            map.put("out_trade_no", orderNo);
            map.put("course_id","64523385");//order.getCourseId()//课程ID
            map.put("total_fee", "0.01");//order.getTotalFee()//价格
            map.put("result_code", resultMap.get("result_code"));//二维码操作状态码
            map.put("code_url", resultMap.get("code_url"));//二维码地址

            return map;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //支付宝支付（沙箱）
    @Override
    public String zfbPay() throws AlipayApiException {
        String format = "json";
        JSONObject json = new JSONObject();
        json.put("setOut_trade_no","20210817010101003");//订单号
        json.put("setSubject","订单名称");
        json.put("setTotal_amount",String.valueOf(new Random().nextInt(100)));
        json.put("product_code","FAST_INSTANT_TRADE_PAY");

        AlipayClient alipayClient = new DefaultAlipayClient(ZfbPayUtils.GatewayUrl,ZfbPayUtils.AppId,ZfbPayUtils.PrivateKey,format,ZfbPayUtils.Charset,ZfbPayUtils.PublicKey,ZfbPayUtils.SignType);
        //PC网页支付使用AlipayTradePagePayRequest传参，下面调用的是pageExecute方法
        AlipayTradePagePayRequest precreateRequest = new AlipayTradePagePayRequest();
        precreateRequest.setReturnUrl(ZfbPayUtils.ReturnUrl);
        precreateRequest.setNotifyUrl(ZfbPayUtils.NotifyUrl);
        precreateRequest.setBizContent(json.toString());
        //log.info("封装请求支付宝付款参数为:{}", JSON.toJSONString(precreateRequest));

        //调用SDK生成表单
        String result = alipayClient.pageExecute(precreateRequest).getBody();

        return result;
    }
}
